import cv2
import os


def crop_image_edges(image_path, output_path, crop_percentage=0.2):
    """
    裁剪单张图片四周一定比例的区域并保存。

    :param image_path: 输入图片路径
    :param output_path: 输出图片路径
    :param crop_percentage: 裁剪的比例 (0-1)，表示裁剪宽度和高度的百分比
    """
    try:
        # 读取图片
        image = cv2.imread(image_path)
        if image is None:
            print(f"Failed to read image: {image_path}")
            return

        h, w, _ = image.shape
        crop_h, crop_w = int(h * crop_percentage), int(w * crop_percentage)

        # 裁剪四周
        cropped_image = image[crop_h:h - crop_h, crop_w:w - crop_w]

        # 保存裁剪后的图片
        cv2.imwrite(output_path, cropped_image)
        print(f"Saved cropped image: {output_path}")

    except Exception as e:
        print(f"Error processing file {image_path}: {e}")


# 示例用法
input_image = "black_template.jpg"  # 输入图片路径
output_image = "crop_black_template.jpg"  # 输出裁剪后图片路径
crop_image_edges(input_image, output_image, crop_percentage=0.2)